#coding=utf-8
from django.shortcuts import render_to_response
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib import auth
from django.contrib.auth.models import User
from member.models import *

def require_login(view):
    def new_view(request, *args, **kwargs):
        if not request.user.is_authenticated():
            return HttpResponseRedirect('/u/login/?next=%s' % request.path)
        return view(request, *args, **kwargs)
    return new_view
    
def authenticate(account = None, password = None):
    """
    登陆验证，account可以为用户名，也可以为Email地址，成功返回用户对象，否则返回None
    """
    #使用用户名登陆
    tmp_user = auth.authenticate(username = account, password = password)
    if tmp_user is not None:
        return tmp_user
    #或使用email登陆
    else:
        try:
            tmp_user = User.objects.get(email__exact = account)
        except User.DoesNotExist:
            return None
        return auth.authenticate(username = tmp_user.username, password = password)

class UsernameExists(Exception):
    pass

class EmailExists(Exception):
    pass
    
class BlockUser(Exception):
    pass
    
class BanedUser(Exception):
    pass
        
def add_member(username, password, email, nickname = None, gender = 'none', description = ''):
    """
    添加用户，成功返回用户对象，否则抛出异常
    """
    if not nickname:
        nickname = username
    
    #判断唯一性
    try:
        user = User.objects.get(username__iexact = username)
        raise UsernameExists, "用户名已存在"
    except User.DoesNotExist:
        pass
    
    try:
        user = User.objects.get(email__iexact = email)
        raise EmailExists, "Email地址已存在"
    except User.DoesNotExist:
        pass
    
    user = User.objects.create_user(username, email, password)
    member = Member(user = user, nickname = nickname, gender = gender, description = description, status = 'active').save()
    
    return user
    
def get_user(user = None, id = None):
    """
    获取用户
    """
    if user is not None:
        id = user.id
    elif (user is None) and (id is not None):
        pass
    else:
        raise User.DoesNotExist
        
    return User.objects.get(id = id)
    
def follow_user(user1, user2):
    """
    user1将user2添加到自己的followlist中
    """
    if is_baned_user(user1, user2):
        raise BanedUser
    else:
        return user1.get_profile().followlist.add(user2)
    
def is_follower(user1, user2):
    """
    判断User1是否是User2的follower，返回值布尔值
    """
    try:
        if user1.get_profile().followlist.get(id = user2.id):
            return True
    except User.DoesNotExist, e:
        return False
        
def is_friend(user1, user2):
    """
    判断user1和user2是否是朋友（就是是否互相follow），返回布尔值
    """
    return (is_follower(user1, user2) and is_follower(user2, user1))
    
def is_baned_user(user1, user2):
    """
    判断User1是否被User2屏蔽，返回值布尔值
    """
    try:
        if user2.get_profile().blacklist.get(id = user1.id):
            return True
    except User.DoesNotExist, e:
        return False
   